// BookRepository.kt
package com.universest.swordholder.data.repository

import androidx.room.RoomDatabase
import com.universest.swordholder.data.UserDatabase
import com.universest.swordholder.data.dao.Book
import com.universest.swordholder.data.dao.BookDao
import kotlinx.coroutines.flow.Flow

class BookRepository(val database: UserDatabase) {

    private val bookDao: BookDao = database.bookDao()
    // 按ID查询书籍（返回Flow，供Compose观察）
    fun getBookById(bookId: Int): Flow<Book?> {
        return bookDao.getBookById(bookId)
    }

    // 获取所有书籍（返回Flow）
    fun getAllBooks(): Flow<List<Book>> {
        return bookDao.getAllBooks()
    }

    // 添加书籍（挂起函数，需在协程中调用）
    suspend fun addBook(book: Book): Long {
        return bookDao.addBook(book)
    }

    // 更新书籍
    suspend fun updateBook(book: Book) {
        bookDao.updateBook(book)
    }

    // 删除书籍
    suspend fun deleteBook(book: Book) {
        bookDao.deleteBook(book)
    }

    // 按ID删除书籍
    suspend fun deleteBookById(bookId: Int) {
        bookDao.deleteBookById(bookId)
    }

    suspend fun updateLastBrowsePassageId(bookId: Int, passageId: Int){
        bookDao.updateLastBrowsePassageId(bookId, passageId)
    }

    suspend fun updateCharCount(bookId: Int, charCount: Int){
        bookDao.updateCharCount(bookId, charCount)
    }

    suspend fun updateLastUpdateTime(bookId: Int, lastUpdateTime: Long = System.currentTimeMillis()){
        bookDao.updateLastUpdateTime(bookId, lastUpdateTime)
    }
}
